package com.wujunshen.orika.convert;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import lombok.extern.slf4j.Slf4j;
import ma.glasnost.orika.MappingContext;
import ma.glasnost.orika.converter.BidirectionalConverter;
import ma.glasnost.orika.metadata.Type;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.commons.lang3.time.DateFormatUtils;

/**
 * @author frank woo(吴峻申) <br>
 * email:<a href="mailto:frank_wjs@hotmail.com">frank_wjs@hotmail.com</a> <br>
 * @date 2020/2/7 5:33 下午 <br>
 */
@Slf4j
public class DateConverter extends BidirectionalConverter<Date, String> {
    private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
    
    @Override
    public String convertTo(
            Date source, Type<String> destinationType, MappingContext mappingContext) {
        return DateFormatUtils.format(source, DATE_FORMAT);
    }
    
    @Override
    public Date convertFrom(
            String source, Type<Date> destinationType, MappingContext mappingContext) {
        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
        try {
            return sdf.parse(source);
        } catch (ParseException e) {
            log.error("exception message is:{}", ExceptionUtils.getStackTrace(e));
        }
        return null;
    }
}
